package com.angel.service.ServiceImpl;

import com.angel.bean.*;
import com.angel.mapper.*;
import com.angel.service.PrescriptionService;
import net.sf.json.JSONArray;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.angel.service.ProductService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestParam;

@Service
public class ProductServiceImpl implements ProductService {

    @Resource
    private ProductDao productDao;
    @Resource
    private VipCardDao vipCardDao;
    @Resource
    private VipInfoDao vipInfoDao;
    @Resource
    private BranchesDao branchesDao;
    @Resource
    private IllCaseDao illCaseDao;
    @Resource
    private PrescriptionDao prescriptionDao;

    @Override
    public int insert(Product product) {
        return productDao.insert(product);
    }

    @Override
    public int insertSelective(Product product) {
        return productDao.insertSelective(product);
    }

    @Override
    public int insertList(List<Product> products) {
        return productDao.insertList(products);
    }

    @Override
    public int update(Product product) {
        return productDao.update(product);
    }

    @Override
    public Product findOne(Product product) {
        List<Product> list = productDao.findProduct(product);
        if (list == null || list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    @Override
    public List<Product> findProduct(Product product) {
        return productDao.findProduct(product);
    }

    @Override
    public List<Product> searchProduct(Product product) {
        return productDao.searchProduct(product);
    }

    @Override
    public int delete(Product product) {
        return productDao.delete(product);
    }

    /***
     * 用户最终结算的处理
     * @param vipInfo 用户vipinfo信息
     * @param employee 当前处理的员工信息
     * @param branches 当前的分店信息
     * @param nochangeTemp 没有改变的商品模板信息
     * @param aloneProduct 单独的商品信息 status存的当前商品的购买数量
     * @param nurseMap 穴位模板信息
     * @return
     */
    @Transactional(rollbackFor = {Exception.class})
    @Override
    public Map settlementPrice(IllCase illCase, VipInfo vipInfo, Employee employee, Branches branches, List<Template> nochangeTemp, List<Product> aloneProduct, List<Map> nurseMap) throws Exception {
        Map result = new HashMap();
        result.put("success", false);
        //先判断会员卡类型，如果是体验卡，则扣除体验卡次数
        VipCard vipCard = new VipCard();
        vipCard.setVipId(vipInfo.getVipId());
        vipCard = vipCardDao.findVipCard(vipCard).get(0);
        if (vipCard.getVipLevel() == 0) {
            //如果是体验卡
            if (aloneProduct.size() > 0) {
                result.put("pay", "该用户是体验卡，商品列表中存在独立商品或者商品模板被更改，不满足体验卡结算条件,请开模板商品后在结算！");
                return result;
            } else {
                //全部是单个商品的结算
                for (int i = 0; i < nochangeTemp.size(); i++) {
                    Template tmp = nochangeTemp.get(i);
                    JSONArray tm = JSONArray.fromObject(tmp.getTemDetail());
                    for (Object jobj : tm) {
                        Map map = (Map) jobj;
                        Integer tpid = Integer.valueOf(map.get("Reid").toString());
                        int count = Integer.valueOf(map.get("productCount").toString());
                        double price = Double.valueOf(map.get("price").toString());
                        //模板中的商品详情
                        Product product = new Product();
                        product.setProductId(tpid);
                        product = productDao.findProduct(product).get(0);
                        Product product1 = new Product();
                        //对应分店的商品详情
                        product1.setBranId(branches.getBranId());
                        product1.setReserve1(product.getReserve1());
                        product1.setProductNo(product.getProductNo());
                        product1 = productDao.findProduct(product1).get(0);
                        int stock = product1.getProStock();
                        product1.setProStock(stock - count);
                        productDao.update(product1);
                    }
                }
                int resum = vipInfo.getRemainTime();
                vipInfo.setRemainTime(resum - 1);
                int res = vipInfoDao.update(vipInfo);
                illCase.setIllCaseState(6);
                int ires = illCaseDao.update(illCase);
                if (res != 0 && ires != 0) {
                    result.put("success", true);
                    result.put("pay", "扣除1次体验次数");
                } else {
                    Exception e = new Exception("处理失败");
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    throw e;
                }
            }

        } else {
            //付费卡
            double countPrice = Double.valueOf(0);
            List<Product> upProduct = new ArrayList<>();
            //模板商品的数量价格
            if (nochangeTemp != null && !nochangeTemp.isEmpty()) {
                for (int i = 0; i < nochangeTemp.size(); i++) {
                    Template tmp = nochangeTemp.get(i);
                    JSONArray tm = JSONArray.fromObject(tmp.getTemDetail());
                    for (Object jobj : tm) {
                        Map map = (Map) jobj;
                        Integer tpid = Integer.valueOf(map.get("Reid").toString());
                        int count = Integer.valueOf(map.get("productCount").toString());
                        double price = Double.valueOf(map.get("price").toString());
                        //模板中的商品详情
                        Product product = new Product();
                        product.setProductId(tpid);
                        product = productDao.findProduct(product).get(0);
                        Product product1 = new Product();
                        //对应分店的商品详情
                        product1.setBranId(branches.getBranId());
                        product1.setReserve1(product.getReserve1());
                        product1.setProductNo(product.getProductNo());
                        product1 = productDao.findProduct(product1).get(0);
                        int stock = product1.getProStock();
                        product1.setProStock(stock - count);
                        countPrice += price * count;
                        upProduct.add(product1);
                    }
                }
            }
            //单个商品的结算
            if (aloneProduct != null && aloneProduct.size() > 0) {
                for (Product p : aloneProduct) {
                    double count = p.getUnitPrice() * p.getState();
                    countPrice += count;
                    Product product1 = new Product();
                    //对应分店的商品详情
                    product1.setBranId(branches.getBranId());
                    product1.setReserve1(p.getReserve1());
                    product1.setProductNo(p.getProductNo());
                    product1 = productDao.findProduct(product1).get(0);
                    int stock = product1.getProStock();
                    product1.setProStock(stock - p.getState());
                    upProduct.add(product1);
                }
            }
            if (nurseMap != null && nurseMap.size() > 0) {
                for (int i = 0; i < nurseMap.size(); i++) {
                    Map nmap = nurseMap.get(i);
                    int count = Integer.valueOf(nmap.get("precount").toString());
                    double price = Double.valueOf(nmap.get("preprice").toString());
                    countPrice += count * price;
                }
            }
            if (Double.valueOf(vipInfo.getBalance()) - (countPrice * (vipCard.getDiscount() / 10)) <= 0) {
                result.put("pay", "该用户卡余额不足，请充值！");
                return result;
            } else {
                //实际支付费用
                double pay = countPrice * (vipCard.getDiscount() / 10);
                //会员卡余额
                double sum = Double.valueOf(vipInfo.getBalance());
                BigDecimal b = new BigDecimal(pay);
                pay = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                //分店的营业额
                double brandsum = 0;
                if (branches.getReserve14() != null) {
                    brandsum = branches.getReserve14();
                }

                vipInfo.setBalance(String.valueOf((sum - pay)));
                branches.setReserve14(brandsum + pay);
                int count = 0;
                for (int i = 0; i < upProduct.size(); i++) {
                    int upres = productDao.update(upProduct.get(i));
                    if (upres != 0) {
                        count++;
                    }
                }
                if (count == upProduct.size()) {
                    int vres = vipInfoDao.update(vipInfo);
                    int bres = branchesDao.update(branches);
                    illCase.setIllCaseState(6);
                    int ires = illCaseDao.update(illCase);
                    Prescription prescription = new Prescription();
                    prescription.setIllCaseId(illCase.getIllCaseId());
                    prescription = prescriptionDao.findAll(prescription).get(0);
                    prescription.setReserve4(String.valueOf(pay));
                    prescriptionDao.update(prescription);
                    if (vres == 0 || bres == 0 || ires ==0) {
                        Exception e = new Exception("处理失败");
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        throw e;
                    } else {
                        result.put("success", true);
                        result.put("pay", "所有原价"+countPrice+"元,会员优惠后实际支付" + pay + "元");
                        return result;
                    }
                } else {
                    Exception e = new Exception("处理失败");
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    throw e;
                }
            }
        }
        return result;
    }

    @Override
    public Map presettlementPrice(IllCase illCase, VipInfo vipInfo, Employee employee, Branches branches, List<Template> nochangeTemp, List<Product> aloneProduct, List<Map> nurseMap) throws Exception {
        Map result = new HashMap();
        result.put("success", false);
        //先判断会员卡类型，如果是体验卡，则扣除体验卡次数
        VipCard vipCard = new VipCard();
        vipCard.setVipId(vipInfo.getVipId());
        vipCard = vipCardDao.findVipCard(vipCard).get(0);
        if (vipCard.getVipLevel() == 0) {
            //如果是体验卡
            if (aloneProduct.size() > 0) {
                result.put("pay", "该用户是体验卡，商品列表中存在独立商品或者商品模板被更改，不满足体验卡结算条件,请开模板商品后在结算！");
                return result;
            } else {
                //全部是单个商品的结算
                for (int i = 0; i < nochangeTemp.size(); i++) {
                    Template tmp = nochangeTemp.get(i);
                    JSONArray tm = JSONArray.fromObject(tmp.getTemDetail());
                    for (Object jobj : tm) {
                        Map map = (Map) jobj;
                        Integer tpid = Integer.valueOf(map.get("Reid").toString());
                        int count = Integer.valueOf(map.get("productCount").toString());
                        double price = Double.valueOf(map.get("price").toString());
                        //模板中的商品详情
                        Product product = new Product();
                        product.setProductId(tpid);
                        product = productDao.findProduct(product).get(0);
                        Product product1 = new Product();
                        //对应分店的商品详情
                        product1.setBranId(branches.getBranId());
                        product1.setReserve1(product.getReserve1());
                        product1.setProductNo(product.getProductNo());
                        product1 = productDao.findProduct(product1).get(0);
                        int stock = product1.getProStock();
                        product1.setProStock(stock - count);
                  //      productDao.update(product1);
                    }
                }
                int resum = vipInfo.getRemainTime();
                vipInfo.setRemainTime(resum - 1);
             //   int res = vipInfoDao.update(vipInfo);
                illCase.setIllCaseState(6);
             //   int ires = illCaseDao.update(illCase);
//                if (res != 0 && ires != 0) {
//                    result.put("success", true);
//                    result.put("pay", "扣除1次体验次数");
//                } else {
//                    Exception e = new Exception("处理失败");
//                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                    throw e;
//                }
            }

        } else {
            //付费卡
            double countPrice = Double.valueOf(0);
            List<Product> upProduct = new ArrayList<>();
            //模板商品的数量价格
            if (nochangeTemp != null && !nochangeTemp.isEmpty()) {
                for (int i = 0; i < nochangeTemp.size(); i++) {
                    Template tmp = nochangeTemp.get(i);
                    JSONArray tm = JSONArray.fromObject(tmp.getTemDetail());
                    for (Object jobj : tm) {
                        Map map = (Map) jobj;
                        Integer tpid = Integer.valueOf(map.get("Reid").toString());
                        int count = Integer.valueOf(map.get("productCount").toString());
                        double price = Double.valueOf(map.get("price").toString());
                        //模板中的商品详情
                        Product product = new Product();
                        product.setProductId(tpid);
                        product = productDao.findProduct(product).get(0);
                        Product product1 = new Product();
                        //对应分店的商品详情
                        product1.setBranId(branches.getBranId());
                        product1.setReserve1(product.getReserve1());
                        product1.setProductNo(product.getProductNo());
                        product1 = productDao.findProduct(product1).get(0);
                        int stock = product1.getProStock();
                        product1.setProStock(stock - count);
                        countPrice += price * count;
                        upProduct.add(product1);
                    }
                }
            }
            //单个商品的结算
            if (aloneProduct != null && aloneProduct.size() > 0) {
                for (Product p : aloneProduct) {
                    double count = p.getUnitPrice() * p.getState();
                    countPrice += count;
                    Product product1 = new Product();
                    //对应分店的商品详情
                    product1.setBranId(branches.getBranId());
                    product1.setReserve1(p.getReserve1());
                    product1.setProductNo(p.getProductNo());
                    product1 = productDao.findProduct(product1).get(0);
                    int stock = product1.getProStock();
                    product1.setProStock(stock - p.getState());
                    upProduct.add(product1);
                }
            }
            if (nurseMap != null && nurseMap.size() > 0) {
                for (int i = 0; i < nurseMap.size(); i++) {
                    Map nmap = nurseMap.get(i);
                    int count = Integer.valueOf(nmap.get("precount").toString());
                    double price = Double.valueOf(nmap.get("preprice").toString());
                    countPrice += count * price;
                }
            }
            if (Double.valueOf(vipInfo.getBalance()) - (countPrice * (vipCard.getDiscount() / 10)) <= 0) {
                double pay = countPrice * (vipCard.getDiscount() / 10);
                result.put("success", false);
                BigDecimal b = new BigDecimal(pay);
                pay = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                result.put("data", pay);
                result.put("msg", "该用户卡余额不足，请充值！");
                return result;
            } else {
                //实际支付费用
                double pay = countPrice * (vipCard.getDiscount() / 10);

                BigDecimal b = new BigDecimal(pay);

                //会员卡余额
                double sum = Double.valueOf(vipInfo.getBalance());
                //分店的营业额
                double brandsum = 0;
                if (branches.getReserve14() != null) {
                    brandsum = branches.getReserve14();
                }

                vipInfo.setBalance(String.valueOf((sum - pay)));
                branches.setReserve14(brandsum + pay);
                pay = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
             //   int count = 0;
//                for (int i = 0; i < upProduct.size(); i++) {
//                //    int upres = productDao.update(upProduct.get(i));
////                    if (upres != 0) {
////                        count++;
////                    }
//                }
         //       if (count == upProduct.size()) {
                 //   int vres = vipInfoDao.update(vipInfo);
                //    int bres = branchesDao.update(branches);
//                    illCase.setIllCaseState(6);
                //    int ires = illCaseDao.update(illCase);
//                    Prescription prescription = new Prescription();
//                    prescription.setIllCaseId(illCase.getIllCaseId());
//                    prescription = prescriptionDao.findAll(prescription).get(0);
//                    prescription.setReserve4(String.valueOf(pay));
                //    prescriptionDao.update(prescription);
//                    if (vres == 0 || bres == 0 || ires ==0) {
//                        Exception e = new Exception("处理失败");
//                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                        throw e;
//                    } else {
                        result.put("success", true);
                        result.put("msg","计算成功");
                        result.put("data",  pay);
                    //    result.put("pay", "所有原价"+countPrice+"元,会员优惠后实际支付" + pay + "元");
                        return result;
//                    }
//                } else {
//                    Exception e = new Exception("处理失败");
//                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                    throw e;
//                }
            }
        }
        return result;
    }


}
